package org.jeecg.modules.run.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jeecg.modules.rule.entity.OpersscFo;
import org.jeecg.modules.rule.service.IOpersscFoService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.run.entity.RunDetail;
import org.jeecg.modules.run.entity.Run;
import org.jeecg.modules.run.vo.RunPage;
import org.jeecg.modules.run.service.IRunService;
import org.jeecg.modules.run.service.IRunDetailService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;

/**
 * @Description: 运行批次表
 * @Author: jeecg-boot
 * @Date: 2019-05-24
 * @Version: V1.0
 */
@RestController
@RequestMapping("/run/run")
@Slf4j
public class RunController {
    @Autowired
    private IRunService runService;
    @Autowired
    private IRunDetailService runDetailService;
    @Autowired
    private IOpersscFoService OpersscFoService;

    /**
     * 分页列表查询
     *
     * @param run
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<Run>> queryPageList(Run run,
                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                            @RequestParam(name = "fdName", required = false) String fdName,
                                            HttpServletRequest req) {
        Result<IPage<Run>> result = new Result<IPage<Run>>();
        QueryWrapper<Run> queryWrapper = QueryGenerator.initQueryWrapper(run, req.getParameterMap());
        if (StringUtils.isNotEmpty(fdName)) {
            List<String> opersscFo = getTabIdListByName(fdName);
            if (opersscFo == null || opersscFo.size() == 0) {
                return null;
            }
            queryWrapper.in("fd_sscid",opersscFo);
        }
        Page<Run> page = new Page<Run>(pageNo, pageSize);
        IPage<Run> pageList = runService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;

    }
    private List<String> getTabIdListByName(String fdName) {
        QueryWrapper<OpersscFo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("fd_name", fdName);
        List<OpersscFo> list =  OpersscFoService.list(queryWrapper);
        if (null == list || list.size() == 0) {
            return new ArrayList<>();
        }

        return covTableInfoString(list);
    }


    private List<String> covTableInfoString(List<OpersscFo> list) {
        List<String> strings = new ArrayList<>();
        for (OpersscFo opersscFo : list) {
            strings.add(opersscFo.getId());
        }
        return strings;
    }

    /**
     * 添加
     *
     * @param runPage
     * @return
     */
    @PostMapping(value = "/add")
    public Result<Run> add(@RequestBody RunPage runPage) {
        Result<Run> result = new Result<Run>();
        try {
            Run run = new Run();
            BeanUtils.copyProperties(runPage, run);

            runService.save(run);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 编辑
     *
     * @param runPage
     * @return
     */
    @PutMapping(value = "/edit")
    public Result<Run> edit(@RequestBody RunPage runPage) {
        Result<Run> result = new Result<Run>();
        Run run = new Run();
        BeanUtils.copyProperties(runPage, run);
        Run runEntity = runService.getById(run.getId());
        if (runEntity == null) {
            result.error500("未找到对应实体");
        } else {
            runService.updateById(run);
            result.success("修改成功!");
        }

        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/delete")
    public Result<Run> delete(@RequestParam(name = "id", required = true) String id) {
        Result<Run> result = new Result<Run>();
        Run run = runService.getById(id);
        if (run == null) {
            result.error500("未找到对应实体");
        } else {
            runService.delMain(id);
            result.success("删除成功!");
        }

        return result;
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatch")
    public Result<Run> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        Result<Run> result = new Result<Run>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.runService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<Run> queryById(@RequestParam(name = "id", required = true) String id) {
        Result<Run> result = new Result<Run>();
        Run run = runService.getById(id);
        if (run == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(run);
            result.setSuccess(true);
        }
        return result;
    }

    //===========================以下是子表信息操作相关API====================================


    /**
     * 通过主表id查询运行详情表
     *
     * @param mainId
     * @return
     */
    @GetMapping(value = "/listRunDetailByMainId")
    public Result<IPage<RunDetail>> queryRunDetailListByMainId(RunDetail detail,
                                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                               @RequestParam(name = "fdName", required = false) String fdName,
                                                              HttpServletRequest req) {
        if (detail.getFdBatchId() != null) {
            Result<IPage<RunDetail>> result = new Result<>();
            QueryWrapper<RunDetail> queryWrapper = QueryGenerator.initQueryWrapper(detail, req.getParameterMap());
            Page<RunDetail> page = new Page<>(pageNo, pageSize);
            IPage<RunDetail> pageList = runDetailService.page(page, queryWrapper);
            result.setSuccess(true);
            result.setResult(pageList);
            return result;


        }


        return null;
    }

    /**
     * 添加运行详情表
     *
     * @param runDetail
     * @return
     */
    @PostMapping(value = "/addRunDetail")
    public Result<RunDetail> addRunDetail(@RequestBody RunDetail runDetail) {
        Result<RunDetail> result = new Result<>();
        try {
            boolean ok = runDetailService.save(runDetail);
            if (ok) {
                result.setSuccess(true);
                result.setMessage("添加运行详情表成功.");
            } else {
                result.setSuccess(false);
                result.setMessage("添加运行详情表失败!");
            }
            return result;
        } catch (Exception e) {
            e.fillInStackTrace();
            result.setSuccess(false);
            result.setMessage("添加运行详情表过程中出现了异常: " + e.getMessage());
            return result;
        }
    }

    /**
     * 编辑运行详情表
     *
     * @param runDetail
     * @return
     */
    @PutMapping("/editRunDetail")
    public Result<RunDetail> editRunDetail(@RequestBody RunDetail runDetail) {
        Result<RunDetail> result = new Result<>();
        try {
            boolean ok = runDetailService.updateById(runDetail);
            if (ok) {
                result.setSuccess(true);
                result.setMessage("更新运行详情表成功.");
            } else {
                result.setSuccess(false);
                result.setMessage("更新运行详情表失败!");
            }
            return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("更新数据过程中出现异常啦: " + e.getMessage());
            return result;
        }
    }

    /**
     * 通过id删除运行详情表
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/deleteRunDetail")
    public Result<RunDetail> deleteRunDetail(@RequestParam(name = "id", required = true) String id) {
        Result<RunDetail> result = new Result<>();
        try {
            boolean ok = runDetailService.removeById(id);
            if (ok) {
                result.setSuccess(true);
                result.setMessage("删除运行详情表成功.");
            } else {
                result.setSuccess(false);
                result.setMessage("删除运行详情表失败!");
            }
            return result;
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("删除运行详情表过程中出现异常啦: " + e.getMessage());
            return result;
        }
    }

    /**
     * 批量删除运行详情表
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatchRunDetail")
    public Result<RunDetail> deleteBatchRunDetail(@RequestParam(name = "ids", required = true) String ids) {
        Result<RunDetail> result = new Result<RunDetail>();
        if (ids == null || "".equals(ids.trim())) {
            result.error500("参数不识别！");
        } else {
            this.runDetailService.removeByIds(Arrays.asList(ids.split(",")));
            result.success("删除成功!");
        }
        return result;
    }


    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(Run run1,HttpServletRequest request, HttpServletResponse response) {
        // Step.1 组装查询条件
        QueryWrapper<Run> queryWrapper = null;
        try {
            queryWrapper = QueryGenerator.initQueryWrapper(run1, request.getParameterMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<RunPage> pageList = new ArrayList<RunPage>();
        List<Run> runList = runService.list(queryWrapper);
        for (Run run : runList) {
            RunPage vo = new RunPage();
            BeanUtils.copyProperties(run, vo);
            List<RunDetail> runDetailList = runDetailService.selectByMainId(run.getId());
            vo.setRunDetailList(runDetailList);
            pageList.add(vo);
        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "运行批次表列表");
        mv.addObject(NormalExcelConstants.CLASS, RunPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("运行批次表列表数据", "导出人:Jeecg", "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<RunPage> list = ExcelImportUtil.importExcel(file.getInputStream(), RunPage.class, params);
                for (RunPage page : list) {
                    Run po = new Run();
                    BeanUtils.copyProperties(page, po);
                    runService.saveMain(po, page.getRunDetailList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }
}
